package cn.q3c.stock.task;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import org.xBaseJ.xBaseJException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

import cn.q3c.stock.object.Stock;

/**
 * 同步新浪历史行情
 * 
 * @author Yoyo
 * 
 */
public class RsyncStockFiles {

	private static Logger logger = Logger.getLogger(RsyncStockFiles.class);

	public static void main(String[] args) throws xBaseJException, IOException,
			ConfigurationException, InterruptedException, ParseException {
		PropertiesConfiguration configuration = new PropertiesConfiguration(
				"stock.properties");

		String savePath = configuration.getString("file.path");// 下载文件本地保存的根目录
		String downloaddate = configuration.getString("download.date");// 下载年份
		
		String startDateStr = StringUtils.substringBefore(downloaddate, "~");
		String endDateStr = StringUtils.substringAfter(downloaddate, "~");
		
		Date sDate = LogToDB.strToDate(startDateStr);
		Date eDate = LogToDB.strToDate(endDateStr);		
		
		int downloadTimes = configuration.getInt("download.times");// 经常会出现防火墙异常，所以重复下载几次

		// 线程池
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
				configuration.getInt("thread.cool"),
				configuration.getInt("thread.max"), 8, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(3),
				new ThreadPoolExecutor.CallerRunsPolicy());

		List<Stock> stockList = LogToDB.getStockList();

			for (int ii = 0; ii < downloadTimes; ii++) {//重复次数
				
				//logger.debug("进入第" + ii + "次下载，year=" + yy); 
				
				Calendar calendar = Calendar.getInstance();//2013
				calendar.setTime(sDate);
				
				while( calendar.getTimeInMillis() >= eDate.getTime()  )
				{
					int dayofweek = calendar.get(Calendar.DAY_OF_WEEK);
					// 周日 周六 跳过
					if (dayofweek == 1 || dayofweek == 7) {
						calendar.add(Calendar.DATE, -1);// 向前
						continue;
					}
					
					
					
					//日历事件
					String year = DateFormatUtils.format(calendar, "yyyy");
					String month = DateFormatUtils.format(calendar, "MM");
					String day = DateFormatUtils.format(calendar, "dd");
					String dateStr = year + "-" + month + "-" + day;
										
					// 上海股票
					for (Stock stock : stockList) {
						String scFlag = stock.getSctype() == Stock.SC_SHANGHAI ? "sh"
								: "sz";

						if ((stock.getSctype() == Stock.SC_SHANGHAI && StringUtils
								.startsWith(stock.getCode(), "60"))
								|| (stock.getSctype() == Stock.SC_SHENZHEN && (StringUtils
										.startsWith(stock.getCode(), "00") || StringUtils
										.startsWith(stock.getCode(), "30")))) {
							String fileName = scFlag + stock.getCode()
									+ "成交明细_" + dateStr + ".xls";
							String fileName2 = scFlag + stock.getCode()
									+ "tdetail_" + dateStr + ".xls";

							URL url = new URL(
									"http://market.finance.sina.com.cn/downxls.php?date="
											+ dateStr + "&symbol=" + scFlag
											+ stock.getCode());
							File file = new File(savePath + dateStr
									+ File.separator + fileName);
							File file2 = new File(savePath + year
									+ File.separator + month + File.separator
									+ day + File.separator + fileName2);
							if (!file.exists() && !file2.exists()) {
								DownloadFiles dfilesThread = new DownloadFiles(
										url, file2);
								threadPool.execute(dfilesThread);
							} else if (file.exists() && !file2.exists()) {
								FileUtils.moveFile(file, file2);
								logger.debug("移动文件：" + file + ";" + file2 + ";"
										+ file.exists() + "," + file2.exists());
							} else {
								logger.debug("文件已存在：" + file2 + ";size="
										+ FileUtils.sizeOf(file2)
										/ FileUtils.ONE_KB + "kb");
							}
						}
					}

					calendar.add(Calendar.DATE, -1);// 向前

					File path = new File(savePath + dateStr + File.separator);
					if (path.exists() && ArrayUtils.isEmpty(path.listFiles())) {
						FileUtils.deleteDirectory(new File(savePath + dateStr
								+ File.separator));
					}
					
					
					
					
					
					
					
					
				}
				
//				//计算日历其实日期
//				//String currentYear = DateFormatUtils.format(new Date(), "yyyy");
//				Calendar calendar = Calendar.getInstance();
//				SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd");				
//				calendar.setTime(dateformat.parse(yy + "-12-31"));				
//				if( calendar.getTimeInMillis() > System.currentTimeMillis() )
//				{
//					calendar.setTime(new Date());
//				}
//				
//				while (true) {//无限循环
//					int dayofweek = calendar.get(Calendar.DAY_OF_WEEK);
//					// 周日 周六 跳过
//					if (dayofweek == 1 || dayofweek == 7) {
//						calendar.add(Calendar.DATE, -1);// 向前
//						continue;
//					}
//
//					//日历事件
//					String year = DateFormatUtils.format(calendar, "yyyy");
//					String month = DateFormatUtils.format(calendar, "MM");
//					String day = DateFormatUtils.format(calendar, "dd");
//					String dateStr = year + "-" + month + "-" + day;
//										
//					// 上海股票
//					for (Stock stock : stockList) {
//						String scFlag = stock.getSctype() == Stock.SC_SHANGHAI ? "sh"
//								: "sz";
//
//						if ((stock.getSctype() == Stock.SC_SHANGHAI && StringUtils
//								.startsWith(stock.getCode(), "60"))
//								|| (stock.getSctype() == Stock.SC_SHENZHEN && (StringUtils
//										.startsWith(stock.getCode(), "00") || StringUtils
//										.startsWith(stock.getCode(), "30")))) {
//							String fileName = scFlag + stock.getCode()
//									+ "成交明细_" + dateStr + ".xls";
//							String fileName2 = scFlag + stock.getCode()
//									+ "tdetail_" + dateStr + ".xls";
//
//							URL url = new URL(
//									"http://market.finance.sina.com.cn/downxls.php?date="
//											+ dateStr + "&symbol=" + scFlag
//											+ stock.getCode());
//							File file = new File(savePath + dateStr
//									+ File.separator + fileName);
//							File file2 = new File(savePath + year
//									+ File.separator + month + File.separator
//									+ day + File.separator + fileName2);
//							if (!file.exists() && !file2.exists()) {
//								DownloadFiles dfilesThread = new DownloadFiles(
//										url, file2);
//								threadPool.execute(dfilesThread);
//							} else if (file.exists() && !file2.exists()) {
//								FileUtils.moveFile(file, file2);
//								logger.debug("移动文件：" + file + ";" + file2 + ";"
//										+ file.exists() + "," + file2.exists());
//							} else {
//								logger.debug("文件已存在：" + file2 + ";size="
//										+ FileUtils.sizeOf(file2)
//										/ FileUtils.ONE_KB + "kb");
//							}
//						}
//					}
//
//					calendar.add(Calendar.DATE, -1);// 向前
//
//					File path = new File(savePath + dateStr + File.separator);
//					if (path.exists() && ArrayUtils.isEmpty(path.listFiles())) {
//						FileUtils.deleteDirectory(new File(savePath + dateStr
//								+ File.separator));
//					}
//				}

		}
	}
}
